<template>
	<view class="page-container" :style="{ height: containerHeight }">
		<view class="slot-container"><slot /></view>
		<!-- <view class="chat-log-space" :style="{ height: bottomHeight + 'px' }"å></view> -->
		<view class="chat-bottom" id="chatBottom">
			<view class="chat-common">
				<view class="chat-common-icon" @tap.stop="switchInput('0')" v-if="vioceController.status == -1"><image class="chat-common-icon-image" src="@/static/images/chat/icon-chat-audio.png" mode="aspectFit"></image></view>
				<view class="chat-common-icon" @tap.stop="switchInput('-1')" v-if="vioceController.status >= 0"><image class="chat-common-icon-image" src="@/static/images/chat/icon-chat-keyboardpng.png" mode="aspectFit"></image></view>

				<view class="chat-common-box" v-if="vioceController.status == -1">
					<!--  -->
					<textarea v-model="chatText" @keyboardheightchange="changeKeyboardHeight" @focus="textareaFocus = true" @blur="textareaFocus = false" class="chat-common-textarea" :disable-default-padding="true" :auto-height="true" :adjust-position="false"></textarea>
				</view>
				<view class="chat-common-box" v-if="vioceController.status >= 0" @touchstart.stop.prevent="touchStartVoice" @touchend.stop.prevent="touchEndVoice" @touchmove.stop.prevent="touchMoveVoice">
					<!--  -->

					<view class="chat-vioce-area">按住 说话</view>
					<view class="chat-vioce-mask" v-show="vioceController.status == 1">
						<view class="chat-vioce-box">
							{{ recorderCurrent + 1 }}秒
							<text>最多可语音{{ recorderMax / 1000 }}秒</text>
						</view>
						<view class="chat-vioce-touch" :style="{ bottom: `calc(-562rpx - ${bottomSafeHeight}px)` }">
							<view class="chat-vioce-cancel" :class="{ cancel: vioceController.inCancel }" id="vioceCancelArea">
								<text>取消</text>
								<text>发送</text>
							</view>
							<view class="chat-vioce-text">松开 发送</view>
							<view class="chat-vioce-touch-icon"><text class="suifont sui-B-yuyin"></text></view>
						</view>
					</view>
				</view>
				<view class="chat-common-icon" @tap.stop="controlBottomChunkShow('emotionShow')"><image class="chat-common-icon-image" src="@/static/images/chat/icon-chat-emotion.png" mode="aspectFit"></image></view>
				<block>
					<view class="chat-common-icon" @tap.stop="controlBottomChunkShow('toolsShow')" v-if="!textareaFocus && !chatText"><image class="chat-common-icon-image" src="@/static/images/chat/icon-chat-more.png" mode="aspectFit"></image></view>
					<view class="chat-common-btn" v-else><view class="chat-common-btn-chunk" @tap.stop="sendMessage">发送</view></view>
				</block>
			</view>
			<!-- <view class="chat-keyboard" :style="{ height: keyboardHeight + 'px' }" :class="{ hide: !bottomChunkShow.keyboardShow || keyboardHeight <= 0 }"></view> -->
			<view class="chat-emotion" :class="{ hide: !bottomChunkShow.emotionShow }"><emoji-picker :height="600" @insert="insertEmoji" :smileyList="smileyList"></emoji-picker></view>
			<view class="chat-tools" :class="{ hide: !bottomChunkShow.toolsShow }" hover-stop-propagation>
				<view class="chat-tools-page">
					<view class="chat-tools-item">
						<view class="chat-tools-item-icon" @tap.stop="openSysAlbum"><image class="chat-tools-item-icon-image" src="@/static/images/chat/icon-chat-picture.png" mode="aspectFit"></image></view>
						<view class="chat-tools-item-text">相册</view>
					</view>
					<view class="chat-tools-item">
						<view class="chat-tools-item-icon" @tap.stop="takePicture"><image class="chat-tools-item-icon-image" src="@/static/images/chat/icon-chat-camera.png" mode="aspectFit"></image></view>
						<view class="chat-tools-item-text">拍照</view>
					</view>
					<view class="chat-tools-item">
						<view class="chat-tools-item-icon" @tap.stop="recordVideo"><image class="chat-tools-item-icon-image" src="@/static/images/chat/icon-chat-video.png" mode="aspectFit"></image></view>
						<view class="chat-tools-item-text">录像</view>
					</view>

					<view class="chat-tools-item" v-if="type == 'single'">
						<view class="chat-tools-item-icon" @tap.stop="sendGift"><image class="chat-tools-item-icon-image" src="@/static/images/chat/icon-chat-gift.png" mode="aspectFit"></image></view>
						<view class="chat-tools-item-text">送礼物</view>
					</view>
					<view class="chat-tools-item">
						<view class="chat-tools-item-icon" @tap.stop="chooseLocation"><image class="chat-tools-item-icon-image" src="@/static/images/chat/icon-chat-location.png" mode="aspectFit"></image></view>
						<view class="chat-tools-item-text">定位</view>
					</view>
					<view class="chat-tools-item">
						<view class="chat-tools-item-icon" @tap.stop="openLog"><image class="chat-tools-item-icon-image" src="@/static/images/chat/icon-chat-log.png" mode="aspectFit"></image></view>
						<view class="chat-tools-item-text">聊天记录</view>
					</view>
				</view>
			</view>
			<view class="chat-bottom-safe" :style="{ height: bottomSafeHeight + 'px' }"></view>
		</view>
		<gift-popup v-model="giftPopupShow" :toUser="toId" @onSuccess="givingSuccess"></gift-popup>
		<chat-popup :popData="menuList" v-model="menuShow" direction="row" :x="menuPos.x" :y="menuPos.y" theme="dark" @tapPopup="tapPopupItem"></chat-popup>
	</view>
</template>

<script>
import Tools from '@/utils/Tools.js';
import giftPopup from '@/components/custom/gift-popup.vue';
import SmileyList from '@/utils/enum/SmileyList.js';
import { mapState } from 'vuex';
import chatPopup from './chat-popup.vue';
export default {
	components: { giftPopup, chatPopup },
	props: {
		type: {
			default: 'single',
			type: String
		},
		recorderMax: {
			default: 15 * 1000,
			type: Number
		},
		toId: {
			default: '',
			type: [Number, String]
		},
		menuList: {
			default() {
				return [];
			},
			type: Array
		},

		menuPos: {
			default() {
				return { x: 0, y: 0 };
			},
			type: Object
		}
	},
	data() {
		return {
			windowHeight: null,
			bottomSafeHeight: 0,
			textareaFocus: false,
			giftPopupShow: false,
			chatText: '',
			bottomChunkShow: {
				emotionShow: false,
				toolsShow: false,
				keyboardShow: false
			},
			vioceController: {
				status: -1,
				cancelArea: null
			},
			bottomHeight: null,
			recorderManager: null,
			audioContext: null,
			recorderTimer: null,
			recorderCurrent: 0,
			smileyList: SmileyList,
			isIos: true,
			slotHeight: null,
			menuShow: false
		};
	},
	watch: {
		textareaFocus: {
			handler(newValue, oldValue) {
				if (newValue) {
					this.controlBottomChunkShow('keyboardShow');
				} else {
					this.controlBottomChunkShow(null);
				}
			}
		},
		bottomChunkShow: {
			async handler(newValue, oldValue) {
				this.$emit('scrollToBottom', {});
			},
			deep: true
		}
	},
	computed: {
		...mapState({
			keyboardHeight: state => state.cache.keyboardHeight || 0
		}),
		containerHeight: function() {
			// #ifdef H5
			return this.windowHeight + 'px';
			// #endif
			// #ifndef H5
			return (this.bottomChunkShow.keyboardShow ? this.windowHeight - this.keyboardHeight : this.windowHeight) + 'px';
			// #endif
		}
	},
	mounted() {
		this.initMedia();
		const system = uni.getSystemInfoSync();
		this.windowHeight = system.windowHeight;
		this.bottomSafeHeight = Tools.getSafeAreaBottomHeight();
	},

	beforeDestroy() {},
	methods: {
		initMedia() {
			if (!this.recorderManager) {
				this.recorderManager = uni.getRecorderManager();
				this.recorderManager.onStop(res => {
					this.touchEndVoice();
					if (!this.vioceController.inCancel) {
						this.initVoiceMsg(res.tempFilePath);
					} else {
						this.$set(this.vioceController, 'inCancel', false);
					}
				});
				this.recorderManager.onStart(res => {
					this.recorderTimer = setInterval(() => {
						this.recorderCurrent += 1;
						if (this.recorderCurrent > this.recorderMax / 1000) {
							this.touchEndVoice();
						}
					}, 1000);
				});
			}
			if (!this.audioContext) {
				this.audioContext = uni.createInnerAudioContext();
				this.audioContext.autoplay = false;
			}
		},
		changeKeyboardHeight(e) {
			console.log(e);
		},

		//切换输入模式
		switchInput(status) {
			this.$set(this.vioceController, 'status', status);
			this.controlBottomChunkShow();
		},
		//控制底部工具显示
		controlBottomChunkShow(showKey = null, bottom = true) {
			const bottomChunkShow = this.bottomChunkShow;
			for (let key in bottomChunkShow) {
				if (showKey && showKey == key && !bottomChunkShow[key]) {
					bottomChunkShow[key] = true;
				} else {
					bottomChunkShow[key] = false;
				}
			}
			this.bottomChunkShow = bottomChunkShow;
			if (bottom) {
				this.$emit('scrollToBottom', {});
			}
		},
		//打开礼物弹出框
		sendGift() {
			this.giftPopupShow = true;
		},
		givingSuccess(data) {
			this.giftPopupShow = false;
			this.refreshUserInfo();
		},
		openSysAlbum() {
			uni.chooseImage({
				count: 6, //默认9
				sourceType: ['album'],
				success: result => {
					for (let i = 0; i < result.tempFilePaths.length; i++) {
						this.initImageMsg(result.tempFilePaths[i]);
					}
				}
			});
		},
		sendMessage() {
			if (this.chatText) {
				const msg = JSON.stringify({
					type: 'text',
					text: this.chatText.trim(),
					randstr: this.$u.guid(32, false) + '-' + this.$u.guid(32, false) + '-' + this.$u.guid(32, false),
					from_vip: { is_vip: this.userInfo.is_vip, vip_file: this.userInfo.vip_file }
				});
				this.chatText = '';
				this.$nextTick(() => {
					this.$emit('confirm', { msg });
				});
			}
		},
		takePicture() {
			uni.chooseImage({
				count: 1, //默认9
				sourceType: ['camera'],
				success: result => {
					for (let i = 0; i < result.tempFilePaths.length; i++) {
						this.initImageMsg(result.tempFilePaths[i]);
					}
				}
			});
		},
		recordVideo() {
			uni.chooseVideo({
				count: 1,
				sourceType: ['camera', 'album'],
				success: res => {
					this.initVideoMsg(res);
				}
			});
		},
		touchStartVoice(e) {
			this.$set(this.vioceController, 'status', 1);
			this.$nextTick(() => {
				if (!this.vioceController.cancelArea) {
					this.$u.getRect('#vioceCancelArea').then(res => {
						this.$set(this.vioceController, 'cancelArea', {
							top: res.top,
							bottom: res.bottom,
							left: res.left,
							right: res.right
						});
						this.startRecord();
					});
				} else {
					this.startRecord();
				}
			});
		},
		touchMoveVoice(e) {
			const points = e.touches[0];
			if (this.vioceController.cancelArea && this.vioceController.status == 1) {
				const inCancel = points.pageX >= this.vioceController.cancelArea.left && points.pageX <= this.vioceController.cancelArea.right && points.pageY >= this.vioceController.cancelArea.top && points.pageY <= this.vioceController.cancelArea.bottom;
				this.$set(this.vioceController, 'inCancel', inCancel);
			}
		},
		touchEndVoice(e) {
			clearInterval(this.recorderTimer);
			this.recorderManager.stop();
			this.vioceController = { cancelArea: this.vioceController.cancelArea, inCancel: this.vioceController.inCancel, status: 0 };
		},
		startRecord() {
			this.recorderCurrent = 0;
			this.recorderManager.start({
				duration: this.recorderMax,
				format: 'mp3'
			});
		},
		//对图片进行处理
		initImageMsg(path) {
			uni.getImageInfo({
				src: path,
				success: res => {
					const msg = JSON.stringify({
						type: 'image',
						text: path,
						width: res.width,
						height: res.height,
						randstr: this.$u.guid(32, false) + '-' + this.$u.guid(32, false) + '-' + this.$u.guid(32, false),
						from_vip: { is_vip: this.userInfo.is_vip, vip_file: this.userInfo.vip_file }
					});
					this.$emit('confirm', { msg });
				}
			});
		},
		chooseLocation() {
			uni.chooseLocation({
				success: res => {
					const { address, longitude, latitude, name } = res;
					const msg = JSON.stringify({
						type: 'location',
						text: address,
						name,
						address,
						longitude,
						latitude,
						randstr: this.$u.guid(32, false) + '-' + this.$u.guid(32, false) + '-' + this.$u.guid(32, false),
						from_vip: { is_vip: this.userInfo.is_vip, vip_file: this.userInfo.vip_file }
					});
					this.$emit('confirm', { msg });
				}
			});
		},
		//对录像进行处理
		initVideoMsg(file) {
			const msg = JSON.stringify({
				type: 'video',
				text: file.tempFilePath,
				width: file.width,
				height: file.height,
				duration: file.duration,
				randstr: this.$u.guid(32, false) + '-' + this.$u.guid(32, false) + '-' + this.$u.guid(32, false),
				from_vip: { is_vip: this.userInfo.is_vip, vip_file: this.userInfo.vip_file }
			});
			this.$emit('confirm', { msg });
		},
		//对音频进行处理
		initVoiceMsg(path) {
			this.audioContext.src = path;
			this.recorderCurrent = 0;
			setTimeout(() => {
				if (this.audioContext.duration <= 2) {
					uni.showToast({
						title: '语音时间过短',
						icon: 'none'
					});
				} else if (this.audioContext.duration < (this.recorderMax / 1000 + 1)) {
					const msg = JSON.stringify({
						type: 'voice',
						text: path,
						duration: this.audioContext.duration,
						randstr: this.$u.guid(32, false) + '-' + this.$u.guid(32, false) + '-' + this.$u.guid(32, false),
						from_vip: { is_vip: this.userInfo.is_vip, vip_file: this.userInfo.vip_file }
					});
					this.$emit('confirm', { msg });
				}
			}, 100);
		},
		insertEmoji(data) {
			console.log(data);
			this.chatText = this.chatText + data.cn;
		},
		openLog() {
			this.$emit('openLog', {});
		},
		showMenuPos() {
			this.menuShow = true;
		},
		hideMenuPos() {
			this.menuShow = false;
		},
		tapPopupItem(e) {
			this.$emit('tapPopupItem', e);
		}
	}
};
</script>

<style lang="scss">
.page-container {
	position: relative;
	display: flex;
	flex-direction: column;
	height: calc(100vh - var(--window-top));
	will-change: height;
	transition: height 0.25s ease;
	transform-origin: bottom;
}

.slot-container {
	position: relative;
	width: 750rpx;
	flex: 1;
}
.chat-bottom {
	// position: fixed;
	bottom: 0;
	left: 0;
	width: 750rpx;
	background-color: #fff;
	z-index: 99;
	flex-shrink: 0;
	.chat-keyboard,
	.chat-emotion,
	.chat-tools {
		will-change: height;
		transition: height 0.3s ease;
		&.hide {
			height: 0 !important;
		}
	}
	.chat-keyboard {
		height: 600rpx;
		background-color: #f6f6f6;
		transition: height 0.2s ease;
	}
	.chat-emotion {
		overflow: hidden;
		height: 600rpx;
	}
	.chat-tools {
		height: 400rpx;
		background-color: #f6f6f6;
		position: relative;
		overflow: hidden;
		&::before {
			content: '';
			height: 1rpx;
			background-color: #dbdbdb;
			width: 750rpx;
			position: absolute;
			top: 0;
			left: 0;
		}
		.chat-tools-page {
			width: 750rpx;
			height: 400rpx;
			display: flex;
			flex-wrap: wrap;
			background-color: #f6f6f6;
			.chat-tools-item {
				width: 187.5rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				height: 200rpx;
				.chat-tools-item-icon {
					width: 104rpx;
					height: 104rpx;
					background: rgba(255, 255, 255, 1);
					border-radius: 23rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					.chat-tools-item-icon-image {
						width: 56rpx;
						height: 56rpx;
					}
				}
				.chat-tools-item-text {
					height: 30rpx;
					font-size: 24rpx;
					font-weight: 400;
					color: rgba(151, 151, 151, 1);
					line-height: 30rpx;
					margin-top: 17rpx;
				}
			}
		}
	}
	.chat-bottom-safe {
		width: 750rpx;
		background-color: #f6f6f6;
	}
	.chat-common {
		min-height: 110rpx;
		background-color: #f6f6f6;
		position: relative;
		padding: 15rpx 0;
		display: flex;
		align-items: flex-end;
		flex: 1;
		.chat-common-icon {
			height: 80rpx;
			width: 90rpx;
			padding: 14rpx 20rpx;
			.chat-common-icon-image {
				width: 50rpx;
				height: 50rpx;
			}
		}
		.chat-common-btn {
			margin-right: 15rpx;
			display: flex;
			align-items: center;
			height: 80rpx;
			.chat-common-btn-chunk {
				height: 60rpx;
				width: 114rpx;
				background-color: $theme-main-color;
				display: flex;
				justify-content: center;
				align-items: center;
				color: #fff;
				font-size: 28rpx;
				font-weight: 400;
				border-radius: 8rpx;
			}
		}
		.chat-common-box {
			flex: 1;
			padding: 0 15rpx;
			background-color: #fff;
			border-radius: 10rpx;
			min-height: 80rpx;
			overflow: hidden;
			.chat-common-textarea {
				min-height: 40rpx;
				width: 100%;
				padding: 19rpx 0;
			}
			.chat-vioce-area {
				width: 100%;
				height: 82rpx;
				font-size: 30rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				font-weight: 700;
			}
			.chat-vioce-mask {
				position: fixed;
				left: 0;
				right: 0;
				top: 0;
				bottom: 0;
				background-color: rgba(0, 0, 0, 0.6);
				z-index: 20;
				.chat-vioce-box {
					height: 120rpx;
					width: 350rpx;
					background-color: $theme-main-color;
					position: absolute;
					top: 45%;
					left: 50%;
					margin-left: -175rpx;
					border-radius: 20rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					color: #fff;
					font-size: 40rpx;
					flex-direction: column;
					text {
						font-size: 24rpx;
					}
				}
				.chat-vioce-touch {
					width: 1300rpx;
					height: 750rpx;
					border-radius: 50% / 50%;
					margin-left: -275rpx;
					position: fixed;
					bottom: -562rpx;
					background-image: radial-gradient(#fff, #9b9b9b);
					border: 10rpx solid #aaaaaa;
					display: flex;
					align-items: center;
					flex-direction: column;

					.chat-vioce-touch-icon {
						font-size: 46rpx;
						color: #5d5d5d;
						margin-top: 20rpx;
					}
					.chat-vioce-text {
						color: #6f7070;
						margin-top: 80rpx;
						font-size: 30rpx;
					}
					.chat-vioce-cancel {
						height: 140rpx;
						width: 140rpx;
						margin-top: -190rpx;
						border-radius: 140rpx;
						display: flex;
						justify-content: center;
						flex-direction: column;
						align-items: center;
						font-size: 24rpx;
						color: #fff;
						background-color: rgba(0, 0, 0, 0.3);
						transition: transform, background-color 0.2s ease;
						&.cancel {
							transform: scale(1.2);
							background-color: rgba(0, 0, 0, 0.4);
						}
					}
				}
			}
		}
		&::before {
			content: '';
			display: block;
			height: 1rpx;
			background-color: #e1e1e1;
			width: 750rpx;
			position: absolute;
			top: 0;
			left: 0;
		}
	}
}
</style>
